﻿using Aop.Api.Encryption;
using System;
using System.Collections.Generic;
using System.DAL;
using System.Dto;
using System.IBLL;
using System.IDAL;
using System.Linq;
using System.Models.Models;
using System.Text;
using System.Threading.Tasks;

namespace System.BLL
{
    public class HouseholdManager : IHouseholdManager
    {
        private CryptoHelper helper;
        public async Task AddHouseholdToStorey(int houseId, string storeyId, string isOwner)
        {
            using (IHouseholeToStoreyService householeToStoreySvc = new HouseholeToStoreyService())
            {
                bool isowner = isOwner == "0" ? false : true;
                await householeToStoreySvc.CreateAsync(new HouseholeToStorey() { HousehoId = houseId,StoreyId = int.Parse(storeyId),IsOwner = isowner });
            }
        }

        public async Task AddNewOneHouseholdAsync(string UserName, string PassWord, string Sex)
        {
            helper = new CryptoHelper();
            using (IHouseholdService householdSvc = new HouseholdService())
            {
                bool sex = Sex == "0" ? false : true;
                await householdSvc.CreateAsync(new Household() { UserName = UserName, PassWord = helper.Encrypt(PassWord), DepartmentRoleId = 2,Sex = sex });
            }
        }

        public async Task CheangTimeByPass(string pass,bool isout)
        {
            using(ITemporaryAccessApplicationService temporaryAccessApplicationSvc = new TemporaryAccessApplicationService())
            {
                var data = temporaryAccessApplicationSvc.GetAllAsync().Where(m => m.EnterOutPass == pass).FirstOrDefault();
                if(data != null)
                {
                    if (!isout)
                    {
                        data.EnterTime = DateTime.Now;
                        await temporaryAccessApplicationSvc.EditAsync(data);
                    }
                    else
                    {
                        data.OutTime = DateTime.Now;
                        await temporaryAccessApplicationSvc.EditAsync(data);
                    }
                }
            }
        }

        public async Task DelHouseholdById(int id)
        {
            using (IHouseholdService householdSvc = new HouseholdService())
            {
                await householdSvc.RemoveAsync(id);
            }
        }

        public async Task DelHouseholdToStoreyById(int id)
        {
            using (IHouseholeToStoreyService householeToStoreySvc = new HouseholeToStoreyService())
            {
                int htsId = householeToStoreySvc.GetAllAsync().Where(m => m.HousehoId == id).FirstOrDefault().Id;
                await householeToStoreySvc.RemoveAsync(htsId);
            }
        }

        public async Task DelMyOneMessageById(int id)
        {
            using(IMessageBoardService messageBoardSvc = new MessageBoardService())
            {
                await messageBoardSvc.RemoveAsync(id);
            }
        }

        public async Task EditOneAcivityByDto(ActivityRegistrationDto dto)
        {
            using(IActivityRegistrationService activityRegistrationSvc = new ActivityRegistrationService())
            {
                var data = activityRegistrationSvc.GetOneByIdAsync(dto.Id);
                data.PartakeCount = int.Parse(dto.PartakeCount);
                data.Phone = dto.phone;
                data.Remark = dto.remark;
                await activityRegistrationSvc.EditAsync(data);
            }
        }

        public async Task EditOneHouseholdByDto(HouseHoldList houseHoldList)
        {
            helper = new CryptoHelper();
            using (IHouseholdService householdSvc = new HouseholdService())
            {
                var data = householdSvc.GetOneByIdAsync(houseHoldList.Id);
                data.UserName = houseHoldList.UserName;
                data.PassWord = helper.Encrypt(houseHoldList.PassWord);
                data.Email = houseHoldList.Email;
                data.Iphone = houseHoldList.PhoneNumber;
                data.Sex = houseHoldList.Sex == "0" ? false : true;
                data.Remark = houseHoldList.Remark;
                await householdSvc.EditAsync(data);
            }
        }

        public async Task EditOneHouseholdToStorey(int id, string isOwner)
        {
            using (IHouseholeToStoreyService householeToStoreySvc = new HouseholeToStoreyService())
            {
                var data = householeToStoreySvc.GetAllAsync().Where(m => m.HousehoId == id).FirstOrDefault();
                if (data !=null)
                {
                    data.IsOwner = isOwner == "0" ? false : true;
                    await householeToStoreySvc.EditAsync(data);
                }
            }
        }

        public async Task ExamineOneTemporaryAccessById(string applicationName, string accessReason, string url, string remark, string guid)
        {
            using(ITemporaryAccessApplicationService temporaryAccessApplicationSvc = new TemporaryAccessApplicationService())
            {
                TemporaryAccessApplication application = new TemporaryAccessApplication()
                {
                    ApplicationName = applicationName,
                    AccessReason = accessReason,
                    Remark = remark,
                    EnterOutPass = guid,
                    ExamineName = url
                };
                await temporaryAccessApplicationSvc.CreateAsync(application);
            }
        }

        public List<HouseHoldList> GetHouseholdLists(int limit, int page, string UserName, string PhoneNumber, string sex, out int datalet)
        {
            using (IHouseholdService householdSvc = new HouseholdService())
            {
                using (IHouseholeToStoreyService householeToStoreySvc = new HouseholeToStoreyService()) 
                {
                    var data = householdSvc.GetAllAsync().Select(m => new HouseHoldList()
                    {
                        Id = m.Id,
                        UserName = m.UserName,
                        PassWord = m.PassWord,
                        Email = m.Email,
                        PhoneNumber = m.Iphone,
                        Sex = m.Sex ? "男" : "女"
                    }).ToList();
                    
                    foreach(var list in data)
                    {
                        var isowner = householeToStoreySvc.GetAllAsync().Where(m => m.HousehoId == list.Id).FirstOrDefault();
                        list.StoreyTitle = GetStoreyById(list.Id);//.Select(m => m.IsOwner)
                        list.IsOwner = isowner == null ? "数据不清" : isowner.IsOwner ? "是" : "不是";
                    }

                    if (!(UserName == "" || UserName == null))
                    {
                        data = data.Where(m => m.UserName.Contains(UserName)).ToList();
                    }

                    if (!(PhoneNumber == "" || PhoneNumber == null))
                    {
                        data = data.Where(m => m.PhoneNumber.Contains(PhoneNumber)).ToList();
                    }
                    if (!(sex == "" || sex == null))
                    {
                        data = data.Where(m => m.Sex.Contains(sex)).ToList();
                    }

                    datalet = data.Count();
                    data = data.OrderBy(m => m.Id).Skip((page - 1) * limit).Take(limit).ToList();
                    return data;
                }
                    
            }
        }

        public List<GetActivityReleaseListDto> GetMyActivityLists(int userId, int limit, int page, string activityName, out int datalet)
        {
            using(IActivityRegistrationService activityRegistrationSvc = new ActivityRegistrationService())
            {
                var activityId = activityRegistrationSvc.GetAllAsync().Where(m => m.UserId == userId).Select(m => m.ActivityID).ToList();
                List<GetActivityReleaseListDto> datas = new List<GetActivityReleaseListDto>();
                GetActivityReleaseListDto data;
                using (IActivityReleaseService activityReleaseSvc = new ActivityReleaseService())
                {
                    foreach(var acId in activityId)
                    {
                        var list = activityReleaseSvc.GetOneByIdAsync(acId);
                        data = new GetActivityReleaseListDto()
                        {
                            Id = acId,
                            activityName = list.ActivityName,
                            activityContent = list.ActivityContent,
                            activityReward = list.ActivityReward,
                        };
                        data.activityTime = DateTime.Parse(list.ActivityTime.ToString()).ToString("yy-MM-dd");
                        bool isnow = DateTime.Now > list.RegistrationDeadline;
                        data.nowTime = isnow.ToString();
                        data.registrationDeadline = DateTime.Parse(list.RegistrationDeadline.ToString()).ToString("yy-MM-dd");
                        data.remark = list.Remark;
                        datas.Add(data);
                    }

                    if (!(activityName == "" || activityName == null))
                    {
                        datas = datas.Where(m => m.activityName.Contains(activityName)).ToList();
                    }

                    datalet = datas.Count();
                    datas = datas.OrderBy(m => m.Id).Skip((page - 1) * limit).Take(limit).ToList();
                    return datas;
                }
            }
        }

        public List<GetMessageListDto> getMyMessageListByDtos(int userId, int limit, int page, string messageText, out int datalet)
        {
            using(IMessageBoardService messageBoardSvc = new MessageBoardService())
            {
                var data = messageBoardSvc.GetAllAsync().Where(m => m.MessageName == userId.ToString()).Select(m => new GetMessageListDto()
                {
                    Id = m.Id,
                    messageText = m.MessageText,
                    createTime = m.CreateTime.ToString()
                }).ToList();
                foreach(var list in data)
                {
                    list.createTime = DateTime.Parse(list.createTime).ToString("yyyy-MM-dd HH:mm:ss");
                }
                if (!(messageText == "" || messageText == null))
                {
                    data = data.Where(m => m.messageText.Contains(messageText)).ToList();
                }

                datalet = data.Count();
                data = data.OrderByDescending(m => m.Id).Skip((page - 1) * limit).Take(limit).ToList();
                return data;
            }
        }

        public string GetNewOneTemporaryAccessByName(string applicationName)
        {
            using(ITemporaryAccessApplicationService temporaryAccessApplicationSvc = new TemporaryAccessApplicationService())
            {
                string url = "#";
                var data = temporaryAccessApplicationSvc.GetAllAsync().Where(m => m.ApplicationName == applicationName).OrderByDescending(m=>m.CreateTime).FirstOrDefault();
                if (data == null)
                {
                    return url;
                }
                if (data.EnterTime != null)
                    return url;
                var createTime = data.CreateTime.ToString("yy-MM-dd");
                var nowTime = DateTime.Now.ToString("yy-MM-dd");
                if(createTime== nowTime)
                {
                    url = data.ExamineName;
                }
                return url;
            }
        }

        public GetTemporaryAccessList getOneAccessByPass(string pass)
        {
            using(ITemporaryAccessApplicationService temporaryAccessApplicationSvc = new TemporaryAccessApplicationService())
            {
                var data = temporaryAccessApplicationSvc.GetAllAsync().Where(m => m.EnterOutPass == pass).Select(m=> new GetTemporaryAccessList() 
                {
                    AccessReason = m.AccessReason,
                    ApplicationName = m.ApplicationName,
                    EnterTime = m.EnterTime==null?"暂未进入":"已进入",
                    OutTime = m.OutTime==null?"暂未出去":"已出去",
                    ApplicationTime = m.CreateTime.ToString()
                }).FirstOrDefault();
                return data;
            }
        }

        public ActivityRegistrationDto GetOneActivityById(int id)
        {
            using (IActivityRegistrationService activityRegistrationSvc = new ActivityRegistrationService())
            {
                var list = activityRegistrationSvc.GetOneByIdAsync(id);
                ActivityRegistrationDto data = new ActivityRegistrationDto()
                {
                    Id = list.Id,
                    PartakeCount = list.PartakeCount.ToString(),
                    phone = list.Phone,
                    remark = list.Remark
                };
                return data;
            }
        }

        public HouseHoldList GetOneHouseholdById(int id)
        {
            helper = new CryptoHelper();
            using (IHouseholdService householdSvc = new HouseholdService())
            {
                using (IHouseholeToStoreyService householeToStoreySvc = new HouseholeToStoreyService())
                {
                    var data = householdSvc.GetOneByIdAsync(id);
                    var isowner = householeToStoreySvc.GetAllAsync().Where(m => m.HousehoId == data.Id).FirstOrDefault();
                    var storeyTitle = GetStoreyById(data.Id);
                    var isOwner = isowner == null ? "数据不清" : isowner.IsOwner ? "是" : "不是";
                    HouseHoldList list = new HouseHoldList()
                    {
                        Id = data.Id,
                        UserName = data.UserName,
                        PassWord = helper.Decrypt(data.PassWord),
                        Email = data.Email,
                        PhoneNumber = data.Iphone,
                        Sex = data.Sex ? "男" : "女",
                        StoreyTitle = storeyTitle,
                        IsOwner = isOwner,
                        Remark = data.Remark
                    };
                    return list;
                }

            }
        }

        public int GetOneHouseholdIdByUserName(string UserName)
        {
            using (IHouseholdService householdSvc = new HouseholdService())
            {
                int Id = householdSvc.GetAllAsync().Where(m => m.UserName == UserName).OrderByDescending(m=>m.CreateTime).FirstOrDefault().Id;
                return Id;
            }
        }

        public string GetStoreyById(int id)
        {
            using (IHouseholeToStoreyService householeToStoreySvc = new HouseholeToStoreyService())
            {
                var storeyId = householeToStoreySvc.GetAllAsync().Where(m => m.HousehoId == id).FirstOrDefault();
                using (IStoreyService storeySvc = new StoreyService())
                {
                    if (storeyId == null)
                        return "暂无房间号";
                    var data = storeySvc.GetOneByIdAsync(storeyId.StoreyId);
                    return data.IssueNumber+data.SeatNunber+data.HoueNunber;
                }
            }
        }

        public List<GetTableSelectStoreyListDto> GettableSelectStoreyList(int limit, int page, string StoreyName, out int datalet)
        {
            using (IStoreyService storeySvc = new StoreyService())
            {
                var data = storeySvc.GetAllAsync().Select(m => new GetTableSelectStoreyListDto()
                {
                    Id = m.Id,
                    StoreyTitle = m.IssueNumber + m.SeatNunber + m.HoueNunber
                }).ToList();

                if (!(StoreyName == "" || StoreyName == null))
                {
                    data = data.Where(m => m.StoreyTitle.Contains(StoreyName)).ToList();
                }
                datalet = data.Count();
                data = data.OrderBy(m => m.Id).Skip((page - 1) * limit).Take(limit).ToList();
                return data;
            }
        }

        public List<GetTemporaryAccessList> GetTemporaryAccessLists(int limit, int page, string ApplicationName, out int datalet)
        {
            using(ITemporaryAccessApplicationService temporaryAccessApplicationSvc = new TemporaryAccessApplicationService())
            {
                var data = temporaryAccessApplicationSvc.GetAllAsync().Select(m => new GetTemporaryAccessList()
                {
                    Id = m.Id,
                    ApplicationName = m.ApplicationName,
                    AccessReason = m.AccessReason,
                    EnterTime = m.EnterTime == null ? "暂未入园" : m.EnterTime.ToString(),
                    OutTime = m.OutTime == null ? "暂未出园" : m.OutTime.ToString(),
                    EnterOutPass = m.EnterOutPass == null ? "--" : m.EnterOutPass,
                    ApplicationTime = m.CreateTime.ToString()
                }).ToList();

                foreach(var list in data)
                {
                    list.ApplicationTime = DateTime.Parse(list.ApplicationTime).ToString("yyyy-MM-dd HH:mm:ss");

                    if (list.EnterTime != "暂未入园")
                    {
                        list.EnterTime = DateTime.Parse(list.EnterTime).ToString("yyyy-MM-dd HH:mm:ss");
                    }
                    if(list.OutTime != "暂未出园")
                    {
                        list.OutTime = DateTime.Parse(list.OutTime).ToString("yyyy-MM-dd HH:mm:ss");
                    }
                }

                if (!(ApplicationName == "" || ApplicationName == null))
                {
                    data = data.Where(m => m.ApplicationName.Contains(ApplicationName)).ToList();
                }
                datalet = data.Count();
                data = data.OrderByDescending(m => m.Id).Skip((page - 1) * limit).Take(limit).ToList();
                return data;
            }
        }
    }
}
